如何在python中实现CRTP功能?
How to implement CRTP functionality in python?
我想从 python 中的基 class 访问派生 class 的成员(变量)。在 c++
中,我可以为此使用 CRTP 设计模式。例如,在 C++ 中,我会这样做:
#include <iostream>
template <class derived>
class Base {
public:
void get_value()
{
double value = static_cast<derived *> (this) -> myvalue_;
std::cout<< "This is the derived value: " << value << std::endl;
}
};
class derived:public Base<derived>{
public:
double myvalue_;
derived(double &_myvalue)
{
myvalue_ = _myvalue;
}
};
用法:
int main(){
double some_value=5.0;
derived myclass(some_value);
myclass.get_value();
// This prints on screen "This is the derived value: 5"
};
有什么方法可以在 python 中实现此功能?
我想要做的是拥有一个单一基础class,它具有一组基于派生class成员的通用函数变量。我想在所有派生的 class 中避免 rewriting/repeating 这组通用函数。
也许你应该退一步问,为什么我们甚至在 C++ 中使用 CRTP。使用 CRTP 的原因是我们可能希望在编译时多态地使用 class 或省略虚函数调用开销。
现在 Python 没有“编译时”,并且因为它不是静态类型,所以所有函数调用本质上都是虚拟的。因此,您将获得与使用常规继承的 CRTP 相同的行为。
class Base(object):
def get_value(self):
print("This is the derived value:", self.value)
class Derived(Base):
def __init__(self, value):
self.value = value
d = Derived(5)
d.get_value() # prints "This is the derived value: 5"
另一方面,如果您希望 CRTP 与 Python3 typing
系统交互,那么您可能需要检查这个问题:Python 3 基 class 返回子 class 实例的工厂方法的类型提示
我不确定它是否是你要找的,但只要 subclass
有一个属性,即使它没有在 baseclass
中定义它也能够通过实例访问它。
class Base(object):
def getValue(self):
print(self.myvalue)
class Derived(Base):
def __init__(self, myvalue):
self.myvalue = myvalue
val = 3
derived = Derived(3)
derived.getValue()
#>3
我想从 python 中的基 class 访问派生 class 的成员(变量)。在 c++
中,我可以为此使用 CRTP 设计模式。例如,在 C++ 中,我会这样做:
#include <iostream>
template <class derived>
class Base {
public:
void get_value()
{
double value = static_cast<derived *> (this) -> myvalue_;
std::cout<< "This is the derived value: " << value << std::endl;
}
};
class derived:public Base<derived>{
public:
double myvalue_;
derived(double &_myvalue)
{
myvalue_ = _myvalue;
}
};
用法:
int main(){
double some_value=5.0;
derived myclass(some_value);
myclass.get_value();
// This prints on screen "This is the derived value: 5"
};
有什么方法可以在 python 中实现此功能?
我想要做的是拥有一个单一基础class,它具有一组基于派生class成员的通用函数变量。我想在所有派生的 class 中避免 rewriting/repeating 这组通用函数。
也许你应该退一步问,为什么我们甚至在 C++ 中使用 CRTP。使用 CRTP 的原因是我们可能希望在编译时多态地使用 class 或省略虚函数调用开销。
现在 Python 没有“编译时”,并且因为它不是静态类型,所以所有函数调用本质上都是虚拟的。因此,您将获得与使用常规继承的 CRTP 相同的行为。
class Base(object):
def get_value(self):
print("This is the derived value:", self.value)
class Derived(Base):
def __init__(self, value):
self.value = value
d = Derived(5)
d.get_value() # prints "This is the derived value: 5"
另一方面,如果您希望 CRTP 与 Python3 typing
系统交互,那么您可能需要检查这个问题:Python 3 基 class 返回子 class 实例的工厂方法的类型提示
我不确定它是否是你要找的,但只要 subclass
有一个属性,即使它没有在 baseclass
中定义它也能够通过实例访问它。
class Base(object):
def getValue(self):
print(self.myvalue)
class Derived(Base):
def __init__(self, myvalue):
self.myvalue = myvalue
val = 3
derived = Derived(3)
derived.getValue()
#>3